﻿using rmTest.Common.AttrUtil;
using rmTest.Common.ExtensionUtil;
using rmTest.Common.ModelUtil;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Reflection;
using System.Text;
using System.Threading.Tasks;

namespace rmTest.Common.DataBaseUtil
{
    public class SqlInstance<T> where T : BaseModel
    {
        public static string QuerySql = string.Empty;
        public static string QuerySqlByPk = string.Empty;
        public SqlInstance()
        {
            QuerySql = InitQuerySqlByT<T>();
        }

        private static string InitQuerySqlByT<T>(bool isQueryAll = true) where T : BaseModel
        {
            string sql = string.Empty;
            //加载模型类型
            Type type = typeof(T);
            //获取类型的属性 TableName 
            string tableName = Activator.CreateInstance<T>().GetModelDisplayValue<T>();
            List<string> columns = new List<string>();
            string condition = string.Empty;
            //获取类型的所有字段，库对应的所有字段
            PropertyInfo[] propertys = type.GetProperties();
            foreach (PropertyInfo property in propertys)
            {
                if (property.IsDefined(typeof(ModelBaseValidateAttribute), true))
                {
                    ModelBaseValidateAttribute modelAttr = property.GetCustomAttribute<ModelBaseValidateAttribute>();
                    if (!modelAttr.Ignored)
                    {
                        string name = property.GetMemberInfoDisplayValue();
                        columns.Add("t." + name);
                    }
                    if (!isQueryAll)
                    {
                        if (modelAttr.IsPrimaryKey)//如果是主键，将作为条件过滤
                        {
                            string name = property.GetMemberInfoDisplayValue();
                            condition = "t.[" + name + "]=@" + name;
                        }
                    }
                }
                else
                {
                    columns.Add("t." + property.Name);
                }
            }
            if (isQueryAll)
            {
                sql = string.Format("select {0} from [dbo].[{1}] t ", string.Join(",", columns.ToArray()), tableName);
            }
            else
            {
                sql = string.Format("select {0} from [dbo].[{1}] t where {2}", string.Join(",", columns.ToArray()), tableName, condition);
            }
            return sql;
        }
    }
}
